<?php
if(!defined('IN_UCHOME')) {
	exit('Access Denied');
}

class LeTao {
	static $db;
	
	function __construct($_SGLOBAL){
		$this->db = $_SGLOBAL['db'];
		
	}
	
	function getBrand(){
		$url = 'http://www.letao.com/brand';
		$html = fetch($url);
		echo $html;
		
	}
	
	function getList($url){
		$html = fetch($url);
		//echo $html;exit;
		//获取当前页的产品链接
		preg_match('/<div id="prodlist">(.+?)<\/div>/is',$html,$u);
		//print_r($u[1]);exit;
		$i = 0;
		if($u[1]){
			//获取网址只要先获取这个商品ID即可，ID为9为数字
			preg_match_all('/\-(\d{9})\-/is',$u[1],$sub_url);
			//print_r($sub_url[1]);exit;
			
			foreach($sub_url[1] as $key => $val){
				//echo $val;
				//$new_url = absolutePath($url, $val);
				//echo $new_url;exit;
				$insertarr = array(
					'pid' => $val
				);
				$sql = 'SELECT pid FROM '.tname('curl_product')." WHERE pid='$val' LIMIT 1";
				$total = $this->db->num_rows($this->db->query($sql));
				if(empty($total)){
					inserttable('curl_product', $insertarr);
					$i++;
				}
			}
			//print_r($sub_url);exit;
			
		}
		
		//查找分页
		preg_match('/<p\s+id=\"pagedowner\">(.+?)<\/p>/is',$html,$p);
		//print_r($p);exit;
		$maxpage = 1;
		if($p[1]){
			//取最大页数
			preg_match_all('/<a[^>]+>(\d+)<\/a>/is',$p[0],$page);
			//print_r($page[1]);exit;
			//sort($page[1]);
			$maxpage = array_pop($page[1]);
			
			//echo $maxpage;exit;
			//拼凑地址
			
			for($i = 2; $i <= $maxpage; $i++){
				$new_url = $url . '-p'.$i;
				$insertarr = array(
					'url' => $new_url
				);
				$sql = 'SELECT id FROM '.tname('curl_page')." WHERE url='$new_url' LIMIT 1";
				$total = $this->db->num_rows($this->db->query($sql));
				if(empty($total)){
					inserttable('curl_page', $insertarr);
				}
			}

		}
		$curl_page = ($maxpage > 1) ? true : false; 
		//exit($html);
		//exit($curl_page);
		return $curl_page;
	}
	function getPage($url){
		
		$html = fetch($url);

		//获取当前页的产品链接
		preg_match('/<div id="prodlist">(.+?)<\/div>/is',$html,$u);
		//print_r($u[1]);exit;
		$i = 0;
		if($u[1]){
			//preg_match_all('/<a.+?href=\"(.+?)\"+[^>]*>.+?<\/a>/is',$u[1],$sub_url);
			preg_match_all('/\-(\d{9})\-/is',$u[1],$sub_url);
			//print_r($sub_url[1]);exit;
			
			foreach($sub_url[1] as $key => $val){
				//echo $val;
				//$new_url = absolutePath($url, $val);
				//echo $new_url;exit;
				$insertarr = array(
					'pid' => $val
				);
				$sql = 'SELECT pid FROM '.tname('curl_product')." WHERE pid='$val' LIMIT 1";
				$total = $this->db->num_rows($this->db->query($sql));
				if(empty($total)){
					inserttable('curl_product', $insertarr);
					$i++;
				}
			}
			//print_r($sub_url);exit;
			
		}
		//updatetable('curl_page', array('state'=>1), array('url'=>$page['url']));
		return true;
	}
	function getProduct($pid){
		$url = 'http://www.letao.com/shoe-'.$pid;
		//$url = 'http://www.letao.com/shoe-propet-854821030-1MBB003-58_83';
		//exit($url);
		$html = fetch($url);
		//echo $html;exit;
		//初始化数组
		$product = array();
		//匹配数组
		$match = array(
			'category'		=> '/<div id=\"ltlinknav\">(.+?)<\/div>/is',
			'goodsname'		=> '/<h1>(.+?)<\/h1>/is',
			'goodsno'		=> '/<th>货号：<\/th><td>(.+?)<\/td>/is',
			'size'			=> '/<ul id=\"shoe_size_list\" class=\"sizechos\"[^>]+>(.+?)<\/ul>/is',
			'oprice'		=> '/<del class=\"gray\">(\d+)元<\/del>/is',
			'cprice'		=> '/<i class=\"ltprice big\">(\d+)元<\/i>/is',
			'color'			=> '/<i class=\"pink\">(.+?)<\/i>/is',
			'detail'		=> '/<table id=\"shoe_property\"[^>]+>(.+?)<\/table>/is',
			'detail_text'	=> '/<div id=\"shoeimages\" class=\"tabdiv\">(.+?)<div id=\"brandsizeouter\">/is',
			'image'			=> '/<ul id=\"imgpoint\">(.+?)<\/ul>/is',
		);
		$match_name = array(
			'category'		=> '分类',
			'goodsname'		=> '货品名',
			'goodsno'		=> '货号',
			'size'			=> '现有库存',
			'oprice'		=> '原价',
			'cprice'		=> '现价',
			'color'			=> '组成颜色',
			'detail'		=> '商品详情',
			'image'			=> '商品图片',
		);
		
		//获取分类，自动处理分类
		preg_match($match['category'],$html,$cat);
		if($cat[1]){
			preg_match_all('/<a.+?href=\"(.+?)\"[^>]*>(.+?)<\/a>/is',$cat[1],$categorys);
			//print_r($categorys);exit;
			unset($categorys[0]);
			$bc = auto_category($categorys);
			$product['brandid'] = $bc[0]['brandid'];
			$brandname =  $bc[0]['brandname'];
			$product['categoryid'] = $bc[1]['categoryid'];
		}
		//print_r($bcid);exit;
		//获取货品名称
		preg_match($match['goodsname'],$html,$t);
		$product['goodsname'] = str_replace(array('&nbsp', ';'), array(' ',''), $t[1]);
		
		//获取货号
		preg_match($match['goodsno'],$html,$gn);
		$product['goodsno'] = Pinyin($gn[1]);

		
		//获取库存
		preg_match($match['size'],$html,$s);
		//echo $match['size'];
		//print_r($s);exit;
		if($s[1]){
			preg_match_all('/<li[^>]+>(\d+)<\/li>/is',$s[1],$gs);
			$product['size'] = implode(',', array_unique($gs[1]));
		}
		
		//获取原价
		preg_match($match['oprice'],$html,$op);
		$product['oprice'] = $op[1];
		
		//获取现价
		preg_match($match['cprice'],$html,$cp);
		$product['cprice'] = $cp[1];
		
		//获取特价
		
		//获取颜色
		preg_match($match['color'],$html,$c);
		$product['color'] = $c[1];
		
		//获取描述
		preg_match($match['detail'],$html,$d);
		$product['detail'] = serialize($detail);
		
		//获取商品描述文字信息
		preg_match($match['detail_text'],$html,$dt);
		if($dt[1]){
			//print_r($dt);
			$dt[1] = preg_replace('/<table[^>]*>.+?<\/table>/is','',$dt[1]);
			$dt[1] = preg_replace('/\s*<div class=\"bigshoeimg\">.+?<\/div>\s*/is','',$dt[1]);
			$dt[1] = preg_replace('/<p style=\"text-align:right; padding:10px 30px 0;\">.+?<\/p>/is','',$dt[1]);
			$dt[1] = preg_replace('/<p class=\"shoe_tip\">.+?<\/p>/is','',$dt[1]);
			$dt[1] = str_replace(array('<div>','	'),'',$dt[1]);
			$dt[1] = str_replace(array('</div>'),"\r\n",$dt[1]);
			
		}
		$product['detail_text'] = $dt[1];
		
		//print_r($product);exit;
		//echo $match['detail'];
		//echo $html;
		//print_r($d);exit;
		$detail_txt = "商品名：\r\n\r\n{$product['goodsname']}\r\n\r\n\r\n商品价格：\r\n\r\n{$product['cprice']}\r\n\r\n\r\n现有库存：\r\n\r\n{$product['size']}\r\n\r\n\r\n组成颜色：\r\n\r\n{$product['color']}\r\n\r\n\r\n商品详情：\r\n\r\n";
		if($d[1]){
			preg_match_all('/<th>(.+?)：<\/th><td>(.+?)<\/td>/is',$d[1],$dd);
			//print_r($dd);exit;
			$detail = array();
			foreach($dd[1] as $key => $val){
				$detail[$val] = $dd[2][$key];
				$detail_txt .= "{$val}：{$dd[2][$key]}\r\n";
			}
			$detail_txt .= "产地：中国";
			//print_r($detail);exit;
		}
		$detail_txt .= "{$product['detail_text']}";
		
		//exit($detail_txt);
		//获取图片地址
		preg_match($match['image'],$html,$i);
		if($i[1]){
			//echo $url;exit;
			//print_r($i[1]);
			preg_match_all('/<img.+?src=\"(.+?)\"[^>]*>/is',$i[1],$ii);
			//print_r($ii);exit;
			foreach($ii[1] as $key => $val){
				$key++;
				$val = str_replace(array('?v2','_3.'),array('', '_6.'), $val);
				$insertarr = array(
					'pid' => $pid,
					'url' => $val,
					'orders' => $key,
				);
				$sql = 'SELECT id FROM '.tname('curl_image')." WHERE url='$val' LIMIT 1";
				$total = $this->db->num_rows($this->db->query($sql));
				if(empty($total)){
					inserttable('curl_image',$insertarr);
				}
			}
		}
		
		foreach($product as $key => $val){
			if(empty($val)){
				exit("key: $key $match_name[$key] 为空，正则为：$match[$key]，采集网址：$url<br /> $html");
			}
		}
		//exit;
		updatetable('curl_product',$product,array('pid'=>$pid));
		//生成文本文件
		$dir = $this->getDir($brandname, $product['goodsno']);
		$path = $dir.$product['goodsno'].'.txt';
		//exit($path);
		$realpath = S_ROOT.'./attachment/'.$path;
		file_put_contents($realpath, $detail_txt);
		//
		return true;
		
	}
	
	function getImage($image){
		//print_r($image);exit;
		//header('Content-type: image/jpeg');
		$html = file_get_contents($image['url']);
		$image['brandname'] = trim($image['brandname']);
		//这里有问题，需要将汉字转成拼音，还不是直接去除
		//exit('这里有问题，需要将汉字转成拼音，还不是直接去除');
		
		//include_once(S_ROOT.'source/function_pinyin.php');
		//$filename = $filename ? $filename : Pinyin($title);
		
		//$image['goodsno'] = preg_replace("/([^a-zA-Z0-9\-])/u",Pinyin("\\1"),$image['goodsno']);
		//$image['goodsno'] = Pinyin($image['goodsno']);
		//echo $image['goodsno'];exit;
		$dir = $this->getDir($image['brandname'], $image['goodsno']);
		$path = $dir.$image['orders'].'.'.fileext($image['url']);
		$realpath = S_ROOT.'./attachment/'.$path;

		file_put_contents($realpath, $html);
		//exit;
		updatetable('curl_image',array('path' => $path,'state' => 1), array('id' => $image['id']));
		return true;
	}
	
	function getDir($brandname, $goodsno){
		$dir = $brandname.'/'.$goodsno.'/';
		//echo $dir;exit;
		if(!is_dir(S_ROOT.'./attachment/'.$dir)){
			mkdir(S_ROOT.'./attachment/'.$dir, 0777, true);
		}
		return $dir;
	}
	function writeDetail($url,$content){
		$h = fopen($url,'w+');
		if(!$h){			
			die("文件 $url 打开失败");			
		}else{
			$strlen = fwrite($h, $content);
		}
		return $strlen;
	}
}

?>